package com.lsa.blog.service.Impl;

import com.lsa.blog.Dao.BlogRepository;
import com.lsa.blog.NotFoundException;
import com.lsa.blog.po.Blog;
import com.lsa.blog.po.Type;
import com.lsa.blog.service.BlogService;
import com.lsa.blog.util.MarkdownUtils;
import com.lsa.blog.util.MyBeanUtils;
import com.lsa.blog.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
@Transactional
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRepository repository;

    /**
     * 根据id查询博客
     * @param id
     * @return
     */
    @Override
    public Blog getBlog(Long id) {
        return repository.findById(id).orElse(null);
    }

    /**
     * 草稿状态的，博客编辑
     * @param id
     * @return
     */
    @Override
    public Blog getAndConvert(Long id) {
        Blog blog = repository.findById(id).orElse(null);
        if (blog == null){
            throw new NotFoundException("博客不存在");
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        repository.updateViews(id);
        return b;
    }

    /**
     * 展示博客信息
     * @param pageable
     * @param blog
     * @return
     */
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return repository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?>cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blog.getTitle())&&blog.getTitle() != null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
                }
                if (blog.getTypeId() != null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"),blog.getTypeId()));
                }
                if (blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));

                return null;
            }
        },pageable);
    }

    /**
     * 展示博客
     * @param pageable
     * @return
     */
    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return repository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                Join join = root.join("tags");
                return cb.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return repository.findByQuery(query,pageable);
    }

    /**
     * 是否选择推荐
     * @param size
     * @return
     */
    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable = PageRequest.of(0,size,sort);
        return repository.findTop(pageable);
    }

    /**
     * 按时间分类博客
     * @return
     */
    @Override
    public Map<String, List<Blog>> archiveBlog() {

        List<String> years = repository.findGroupYear();
        Map<String, List<Blog>>map = new HashMap<>();
        for(String year : years){
            map.put(year,repository.findByYear(year));
        }
        return map;
    }

    /**
     * 博客总数
     * @return
     */
    @Override
    public Long countBlog() {
        return repository.count();
    }

    /**
     * 保存博客
     * @param blog
     * @return
     */
    @Override
    public Blog saveBlog(Blog blog) {
        if (blog.getId() == null){
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        }else {
            blog.setUpdateTime(new Date());
        }
        return repository.save(blog);
    }

    /**
     * 修改博客，根据id
     * @param id
     * @param blog
     * @return
     */
    @Override
    public Blog updateBlog(Long id,Blog blog) {
        Blog b = repository.findById(id).orElse(null);
        if (blog == null){
            throw new NotFoundException("该博客不存在");
        }
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return saveBlog(b);
    }

    /**
     * 删除博客通过id
     * @param id
     */
    @Override
    public void deleteBlog(Long id) {
        repository.deleteById(id);

    }
}
